﻿// 配合zTree的js使用，不能单独使用

// 原生函数封装
function ZTreePrototype() {
    // 原生
    this.GetCheckedNode = function() {
        return this.Tree.getCheckedNodes();
    }

    this.GetSelectedNodes = function () {
        return this.Tree.getSelectedNodes();
    }

    this.GetNodeByParam = function (key, value, parentNode) {
        return this.Tree.getNodesByParam(key, value, parentNode);
    }

    this.GetNodesByFilter = function (filter, isSingle, parentNode, invokeParam) {
        return this.Tree.getNodesByFilter(filter, isSingle, parentNode, invokeParam);
    }

    this.CheckNode = function(treeNode, checked, checkTypeFlag, callbackFlag) {
        return this.Tree.checkNode(treeNode, checked, checkTypeFlag, callbackFlag);
    }

    /**
     * 
     * @param {} node 
     * @param {} sonFlag 是否展开子节点，对异步没用。
     * @param {} callbackFlag 
     * @returns {} 
     */
    this.ExpandNode = function (node, sonFlag, callbackFlag) {
        return this.Tree.expandNode(node, true, sonFlag, callbackFlag);
    }

    this.ExpandAsyncNode = function (node, callbackFlag) {
        if (node.isChildrenLoad === true && node.isParent) {
            return true;
        }

        var r = this.ReAsyncChildNodes(node, "refresh", false);
        return r;
    }

    this.FoldNode = function (node, sonFlag, callbackFlag) {
        return this.Tree.expandNode(node, false, sonFlag, callbackFlag);
    }

    this.Refresh = function() {
        return this.Tree.refresh();
    }

    this.Destroy = function() {
        return this.Tree.destroy();
    }

    this.ReAsyncChildNodes = function(node, reloadType, isSilent, callback) {
        return this.Tree.reAsyncChildNodes(node, reloadType, isSilent, callback);
    }

    // 需要导入exhide拓展包
    this.HideNode = function (node) {
        return this.Tree.hideNode(node);
    }

    this.ShowNode = function (node) {
        return this.Tree.showNode(node);
    }

    this.HideNodes = function (nodes) {
        return this.Tree.hideNodes(nodes);
    }

    this.ShowNodes = function (nodes) {
        return this.Tree.showNodes(nodes);
    }

    this.ShowNodesWithChildren = function (nodes) {
        this.ShowNodes(nodes);
        for (var i = 0; i < nodes.length; i++) {
            this.ShowNodesWithChildren(nodes[i].children);
        }
    }

    // 封装
    this.GetLeafCheckedNodes = function () {
        return this.GetCheckedNode().filter(function (node) {
            return node.isParent === false;
        });
    }

    this.GetTopCheckedNodes = function () {
        var checkedArray = this.GetCheckedNode();
        var topArray = [];
        for (var i = 0; i < checkedArray.length; i++) {
            var node = checkedArray[i];
            var paths = node.getPath();
            var repeat = false;
            for (var j = paths.length - 2; j >= 0; j--) { // 遍历父节点是否已选中
                if (paths[j].checked) {
                    repeat = true;
                    break;
                }
            }
            if (!repeat) {
                topArray.push(node);
            }
        }
        return topArray;
    }

    this.GetNodeByName = function(name) {
        return this.GetNodeByParam("name", name);
    }

    /**
     * 获取根节点列表
     * @returns {} 
     */
    this.GetTopNodes = function() {
        return this.GetNodeByParam("level", 0);
    }
}


function ZTreeObject(TreeId, TreeData, SearchId) {
    this.TreeId = TreeId;
    this.SearchId = SearchId;
    this.TreeSelector = $("#" + TreeId);
    this.SearchSelector = $("#" + SearchId);
    this.Tree = null; // 
    this.DefaultTreeData = TreeData; // 数据
    this.WaitToSelectNode = null;
    this.SearchMode = null; // 搜索模式
    this.CheckBoxStatus = false;
    this.ExpandAllOidArray = [];
    this.Setting = {
        "data": {
            "key": {
                "name": "text",
                "title": "title",
                "icon": "icon"
            }
        },
        "check": {
            "enable": true,
            "chkboxType": {
                "Y": "",
                "N": ""
            }
        },
        "callback": {
        },
        "view": {
            "expandSpeed":""
        }
    };

    this.InitTree = function () {
        this.TreeSelector.addClass("ztree");
        $.fn.zTree.init(this.TreeSelector, this.Setting, this.DefaultTreeData);
        this.Tree = $.fn.zTree.getZTreeObj(this.TreeId);
        return this;
    }

    this.InitSelectParentNotChildrenTree = function () {
        // 递归禁用子节点复选框
        function disableChildrenCheckbox(nodes) { 
            for (var j = 0; j < nodes.length; j++) {
                var node = nodes[j];
                node.chkDisabled = true;
                disableChildrenCheckbox(node.children);
            }
        }
        // 递归启用子节点复选框
        function enableChildrenCheckbox(nodes) { 
            for (var j = 0; j < nodes.length; j++) {
                var node = nodes[j];
                node.chkDisabled = false;
                if (node.checked === false) { // 被启用节点被选中，则子节点不启用复选框
                    enableChildrenCheckbox(node.children);
                }
            }
        }
        var setting = this.Setting;
        setting.callback["onCheck"] = function(event, treeId, treeNode) { // 复选框监听事件
            if (treeNode.checked === true) {
                disableChildrenCheckbox(treeNode.children);
            } else {
                enableChildrenCheckbox(treeNode.children);
            }
            this.Refresh();
        }.bind(this);
        this.InitTree();
    }

    this.InitJustSelectChildrenTree = function() {
        var setting = this.Setting;
        setting.check.chkboxType = { "Y": "ps", "N": "ps" };
        this.InitTree();
    }

    this.InitAsyncTree = function (asyncSetting) {
        if (typeof asyncSetting === "undefined") {
            console.error()("初始化失败，没有传入异步参数。");
            return;
        }
        this.TreeSelector.addClass("ztree");
        var setting = this.Setting;
        setting.async = asyncSetting;
        $.fn.zTree.init(this.TreeSelector, this.Setting);
        this.Tree = $.fn.zTree.getZTreeObj(this.TreeId);
        return this;
    }

    this.InitAsyncJustSelectChildrenTree = function (asyncSetting) {
        var setting = this.Setting;
        setting.check.chkboxType = { "Y": "ps", "N": "ps" };
        return this.InitAsyncTree(asyncSetting);
    }

    /**
     * 关键字搜索
     * @returns {} 
     */
    this.SearchKeyFromTree = function () {
        // 递归搜索树
        var searchTree = function(node, key) {
            var childrenContain = false;
            for (var i = 0; i < node.children.length; i++) {
                if (searchTree(node.children[i], key)) {
                    childrenContain = true;
                }
            }
            if (childrenContain === true) { // 子节点包含
                this.ShowNode(node);
                return true;
            } else if (searchNode(node, key)) { // 本节点包含
                this.ShowNode(node);
                return true;
            } else { // 都不包含
                this.HideNode(node);
                node.open = false;
                return false;
            }
        }.bind(this);
        // 递归搜索节点
        var searchNode = function (node, key) {
            if (node.oid.indexOf(key) > -1) {
                return true;
            } else if (node.text.indexOf(key) > -1) {
                return true;
            } else if (node.title.indexOf(key) > -1) {
                return true;
            } else if (node.name.indexOf(key) > -1) {
                return true;
            } else {
                return false;
            }
        }.bind(this);

        var key = this.SearchSelector.val();
        if (key.trim() === "") {
            this.ShowNodesWithChildren(this.GetTopNodes());
        } else {
            var trees = this.GetTopNodes();
            for (var i = 0; i < trees.length; i++) {
                searchTree(trees[i], key);
            }
        }
        this.Refresh();
    }

    // 搜索框回车事件
    this.SearchSelector.keydown(function (e) {
        if (e.which === 13) {
            this.SearchKeyFromTree();
            return false;
        }
        return true;
    }.bind(this));
}

ZTreeObject.prototype = new ZTreePrototype();

function AsyncSetting() {
    this.autoParam = [];
    this.contentType = "application/x-www-form-urlencoded";
    this.enable = true;
    this.dataType = "text";
    this.otherParam = [];
    this.type = "post";
    this.headers = {};
    this.xhrFields = {};
    this.url = "";
    this.dataFilter = null;
}
